package com.mission.schedule.appwidget;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mission.schedule.R;
import com.mission.schedule.activity.MainActivity;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.CYTXBean;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.entity.LocateAllNoticeTable;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.service.LocalSynService;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.RepeatSetChildEndUtils;
import com.mission.schedule.utils.SharedPrefUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by liwei on 2016/10/24.
 */

public class WidgetA extends AppWidgetProvider {


    public final static String EXTRA_BUTTON_ITEM = "BUTTON_ITEM";
    public final static String CLICK_ITEM_ACTION = "LISTVIEW_ONCLICK";
    public final static String CLICK_15 = "BUTTON_CLICK_DJS_ONE";
    public final static String CLICK_30 = "BUTTON_CLICK_DJS_TWO";
    public final static String CLICK_MONTH = "BUTTON_CLICK_MONTH";


    private List<Map<String, String>> mList = new ArrayList<>();
    List<Map<String, String>> unlist = new ArrayList<>();
    List<Map<String, String>> todaylist = new ArrayList<>();
    List<Map<String, String>> endlist = new ArrayList<>();
    List<CYTXBean.QcBean> qcBeanList = new ArrayList<>();
    List<CYTXBean.DjsBean> djsBeanList = new ArrayList<>();

    SharedPrefUtil sharedPrefUtil = null;

    String soundstate;
    String wakestate;

    private Vibrator vibrator;

    String delaytime = "";
    boolean none = true;


    // 当 widget 被初次添加 或者 当 widget 的大小被改变时，被调用
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {

    }

    // widget被删除时调用
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    // 第一个widget被创建时调用
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
    }

    // 最后一个widget被删除时调用
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        String userid = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "");
        Intent LocalSyni = new Intent(context, LocalSynService.class);
        if (intent != null && !userid.isEmpty()) {
            String date, showTime, djs;
            String centime = DateUtil.formatDateTimeSs(new Date());

            cjson(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CYTXJSON, ""));

            switch (intent.getAction()) {
                case CLICK_ITEM_ACTION:
                    Bundle extras = intent.getExtras();
                    int position = extras.getInt(EXTRA_BUTTON_ITEM, -1);
                    try {
                        unlist.clear();
                        todaylist.clear();
                        mList.clear();
                        endlist.clear();

                        unlist = App.getDBcApplication().queryAllSchData(901, 0, 0);
                        todaylist = App.getDBcApplication().queryAllSchData(907, 0, 0);

                        mList.addAll(unlist);
                        mList.addAll(todaylist);

                        ArrayList<Map<String, String>> list = App.getDBcApplication().queryAllSchData(-4, 0, 0);
                        if (mList.size() == 0 && list.size() > 0) {
                            for (int i = 0; i < 7; i++) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.add(Calendar.DATE, +i);
                                String datea = DateUtil.formatDate(calendar.getTime());
                                mList.addAll(App.getDBcApplication().queryCalenderData(datea));

                                if (mList.size() > 0) {
                                    break;
                                }
                            }
                        }

                        for (int i = 0; i < mList.size(); i++) {
                            if (Integer.valueOf(mList.get(i).get(ScheduleTable.schIsEnd)) == 1) {
                                endlist.add(mList.get(i));
                            }
                        }

                        for (int i = 0; i < endlist.size(); i++) {
                            for (int j = 0; j < mList.size(); j++) {
                                if (endlist.get(i).get(ScheduleTable.schID).equals(mList.get(j).get(ScheduleTable.schID))) {
                                    mList.remove(j);
                                }
                            }
                        }
                        if (endlist.size() > 0) {
                            mList.addAll(endlist);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (mList.size() > 0) {
                        none = true;
                        if (position != -1) {

                            vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                            // isNetWork();
                            sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);

                            //com.mission.schedule

                            if (isServiceRunning(context, "com.mission.schedule.service.ClockService") ||
                                    isServiceRunning(context, "com.mission.schedule.service.MinAndMaxService")) {

                                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.APPWIDGETUPLOADTYPE, "1");
                                if (Integer.valueOf(mList.get(position).get(ScheduleTable.schcRecommendId)) > 0
                                        && Integer.valueOf(mList.get(position).get(ScheduleTable.schAID)) == 0) {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0");
                                } else {
                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "1");
                                }

                                endCalender(mList.get(position), context);
                            }
                        }

                    }
                    break;
                case CLICK_MONTH:
                    sharedPrefUtil.putBoolean(ShareFile.MONTH_SHOW, true).commit();
                    Intent intent_m = new Intent(context, MainActivity.class);
                    intent_m.putExtra("ismonth", true);
                    intent_m.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent_m);
                    break;
                case CLICK_15:
                    if (djsBeanList.size() > 2) {
                        String dj1;
                        if (djsBeanList.get(0).type == 2) {
                            if ((djsBeanList.get(0).number / 0.5) % 2 == 1) {
                                dj1 = djsBeanList.get(0).number + "";
                            } else {
                                dj1 = (int) djsBeanList.get(0).number + "";
                            }
                        } else {
                            dj1 = (int) djsBeanList.get(0).number + "";
                        }
                        djs1 = dj1 + "\n" + djsBeanList.get(0).timetype;
                    }
                    String[] ds1 = djs1.split("\n");
                    if (ds1.length == 2) {
                        if (ds1[1].equals("分钟")) {
                            date = DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil
                                    .parseDateTime(DateUtil.formatDateTime(new Date())).getTime() + Integer.valueOf(ds1[0]) * 60 * 1000)));
                            showTime = (int) Integer.valueOf(ds1[0]) + "";
                        } else {
                            date = DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil
                                    .parseDateTime(DateUtil.formatDateTime(new Date())).getTime() + Integer.valueOf(ds1[0]) * 60 * 1000)));
                            if (ds1[0].split("\\.")[1].equals("5")) {
                                showTime = ds1[0];
                            } else {
                                showTime = (int) Integer.valueOf(ds1[0]) + "";
                            }
                        }

                        App.getDBcApplication().insertScheduleData(
                                showTime + ds1[1] + "倒计时提醒", DateUtil.formatDate(DateUtil.parseDate(date)),
                                date.substring(11, 16), 1, 0, 1, 0, 0, 0, 0, centime, "", 0, "", "", 0, "", "", 1, 0, 0,
                                "到点提醒", "g_001", "", 0, 0, 0, "", "", 0, 0, 0, 0, "", "0", "0");
                        showtoast(context, "创建成功\n" + showTime + ds1[1] + "后提醒您");
                    } else {
                        date = DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(new Date())).getTime() + 15 * 60 * 1000)));
                        App.getDBcApplication().insertScheduleData("15分钟倒计时提醒", DateUtil.formatDate(DateUtil.parseDate(date)),
                                date.substring(11, 16), 1, 0, 1, 0, 0, 0, 0, centime, "", 0, "", "", 0, "", "", 1, 0, 0,
                                "到点提醒", "g_001", "", 0, 0, 0, "", "", 0, 0, 0, 0, "", "0", "0");
                        showtoast(context, "创建成功\n15分钟后提醒您");
                    }
                    LocalSyni.setAction("LocalSynService");
                    LocalSyni.putExtra("isMinLocal", true);
                    LocalSyni.setPackage(context.getPackageName());
                    context.startService(LocalSyni);
                    updateLoginDate(context);
                    break;
                case CLICK_30:
                    if (djsBeanList.size() > 2) {
                        String dj2;
                        if (djsBeanList.get(1).type == 2) {
                            if ((djsBeanList.get(1).number / 0.5) % 2 == 1) {
                                dj2 = djsBeanList.get(1).number + "";
                            } else {
                                dj2 = (int) djsBeanList.get(1).number + "";
                            }
                        } else {
                            dj2 = (int) djsBeanList.get(1).number + "";
                        }
                        djs2 = dj2 + "\n" + djsBeanList.get(1).timetype;
                    }
                    String[] ds2 = djs2.split("\n");
                    if (ds2.length == 2) {
                        if (ds2[1].equals("分钟")) {
                            date = DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil
                                    .parseDateTime(DateUtil.formatDateTime(new Date())).getTime() + Integer.valueOf(ds2[0]) * 60 * 1000)));
                            showTime = (int) Integer.valueOf(ds2[0]) + "";
                        } else {
                            date = DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil
                                    .parseDateTime(DateUtil.formatDateTime(new Date())).getTime() + Integer.valueOf(ds2[0]) * 60 * 1000)));
                            if (ds2[0].split("\\.")[1].equals("5")) {
                                showTime = ds2[0];
                            } else {
                                showTime = (int) Integer.valueOf(ds2[0]) + "";
                            }
                        }

                        App.getDBcApplication().insertScheduleData(
                                showTime + ds2[1] + "倒计时提醒", DateUtil.formatDate(DateUtil.parseDate(date)),
                                date.substring(11, 16), 1, 0, 1, 0, 0, 0, 0, centime, "", 0, "", "", 0, "", "", 1, 0, 0,
                                "到点提醒", "g_001", "", 0, 0, 0, "", "", 0, 0, 0, 0, "", "0", "0");
                        showtoast(context, "创建成功\n" + showTime + ds2[1] + "后提醒您");
                    } else {
                        date = DateUtil.formatDateTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil
                                .parseDateTime(DateUtil.formatDateTime(new Date())).getTime() + 30 * 60 * 1000)));
                        App.getDBcApplication().insertScheduleData("30分钟倒计时提醒", DateUtil.formatDate(DateUtil.parseDate(date)),
                                date.substring(11, 16), 1, 0, 1, 0, 0, 0, 0, centime, "", 0, "", "", 0, "", "", 1, 0, 0,
                                "到点提醒", "g_001", "", 0, 0, 0, "", "", 0, 0, 0, 0, "", "0", "0");
                        showtoast(context, "创建成功\n30分钟后提醒您");
                    }
                    LocalSyni.setAction("LocalSynService");
                    LocalSyni.putExtra("isMinLocal", true);
                    LocalSyni.setPackage(context.getPackageName());
                    context.startService(LocalSyni);
                    updateLoginDate(context);
                    break;
            }
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(context, WidgetA.class));
            onUpdate(context, appWidgetManager, ids);
        } else {
            super.onReceive(context, intent);
        }


    }

    private void showtoast(Context context, String message) {
        Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
        int textview_id = Resources.getSystem().getIdentifier("message", "id", "android");
        ((TextView) toast.getView().findViewById(textview_id)).setGravity(Gravity.CENTER);
        toast.show();
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param mContext
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }


    private void endCalender(Map<String, String> mMap, final Context context) {
        try {
            if ("0".equals(mMap.get(ScheduleTable.schIsEnd))) {
                soundstate = sharedPrefUtil.getString(context,
                        ShareFile.USERFILE, ShareFile.ENDSOUNDSTATE,
                        "0");
                wakestate = sharedPrefUtil
                        .getString(context, ShareFile.USERFILE,
                                ShareFile.ENDWAKESTATE, "0");
                if ("0".equals(soundstate)) {
                    MediaPlayer mediaPlayer = mediaPlayer = new MediaPlayer();
                    AssetFileDescriptor fileDescriptor = context
                            .getAssets().openFd("complete.mp3");
                    mediaPlayer.setDataSource(
                            fileDescriptor.getFileDescriptor(),
                            fileDescriptor.getStartOffset(),
                            fileDescriptor.getLength());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
                if ("0".equals(wakestate)) {
                    long[] pattern = {100, 400}; // 停止 开启 停止 开启
                    vibrator.vibrate(pattern, -1); // 重复两次上面的pattern
                    // 如果只想震动一次，index设为-1
                }
            }
            if ("0".equals(mMap.get(ScheduleTable.schRepeatID))) {
                updateScheduleRead1(mMap, ScheduleTable.schRead);
            } else {
                updateScheduleRead2(mMap, ScheduleTable.schRead, ScheduleTable.schRepeatLink);
            }
            updateScheduleIsEnd(mMap, ScheduleTable.schIsEnd, ScheduleTable.schUpdateState);
            updateSchClock(mMap, LocateAllNoticeTable.isEnd);
            QueryAlarmData.writeAlarm(context.getApplicationContext());
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ENDUPDATETIME, DateUtil.formatDateTimeSs(new Date()));

            Intent intent_app = new Intent();
            intent_app.setAction("appwidget");
            intent_app.putExtra("aappwidget", true);
            context.sendBroadcast(intent_app);

            Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    String updatetime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ENDUPDATETIME, DateUtil.formatDateTimeSs(new Date()));
                    delaytime = DateUtil.formatDateTimeSs(new Date());
                    if (DateUtil.parseDateTimeSs(delaytime).getTime() - DateUtil.parseDateTimeSs(updatetime).getTime() >= 1000) {
//                        UpLoadData(context);
                    }
                }
            };
            timer.schedule(timerTask, 1000);
            timer.cancel();

            if (mMap.get(ScheduleTable.schpisEnd).equals("0")) {
                try {
                    endTask(Integer.valueOf(mMap.get(ScheduleTable.schIsEnd)), context, mMap.get(ScheduleTable.schSourceDesc));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void endTask(final int type, final Context context, final String titleid) {
        StringRequest request1 = new StringRequest(Request.Method.POST, URLConstants.清单留言公开方公开发送url下行, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("uId", sharedPrefUtil
                        .getString(context, ShareFile.USERFILE,
                                ShareFile.USERID, "0"));
                map.put("titleId", titleid);
                if (type == 2) map.put("type", "0");
                else map.put("type", "1");
                return map;
            }
        };
        request1.setTag("updateFrendTaskIsDown");
        request1.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 1.0f));
        App.getHttpQueues().add(request1);
    }


    private void updateSchClock(Map<String, String> mMap, String key) {
        try {
            String value = "0";
            String key1 = "";
            Map<String, String> upMap = new HashMap<String, String>();
            if (key.equals("isEnd")) {
                key1 = "schIsEnd";
            } else if (key.equals("postpone")) {
                key1 = "schIsPostpone";
            }
            if ("1".equals(mMap.get(key1)))
                value = "1";
            else
                value = "0";
            upMap.put(key, value);
            App.getDBcApplication().updateSchIsEnd(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateScheduleRead1(Map<String, String> mMap, String key) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
//            myschedule_listview.hiddenRight();
            // if ("0".equals(mMap.get(key)))
            value = mMap.get(ScheduleTable.schRead);
            // else
            // value = "1";
            upMap.put(key, value);
            App.getDBcApplication().updateScheduleData1(upMap,
                    "where schID=" + mMap.get("schID"));
            mMap.put(key, value);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateScheduleRead2(Map<String, String> mMap, String key,
                                     String key1) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
//            myschedule_listview.hiddenRight();
            // if ("0".equals(mMap.get(key)))
            value = mMap.get(key);
            // else
            // value = "1";
            upMap.put(key, value);
            upMap.put(key1, "3");
            App.getDBcApplication().updateScheduleData(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    RepeatSetChildEndUtils repeatSetChildEndUtils = new RepeatSetChildEndUtils();

    private void updateScheduleIsEnd(Map<String, String> mMap, String key,
                                     String key1) {
        try {
            if ("1".equals(mMap.get(ScheduleTable.schRepeatLink))
                    || "3".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                repeatSetChildEndUtils.setParentStateIsEnd(mMap);
            }
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
//            myschedule_listview.hiddenRight();
            if ("0".equals(mMap.get(key)))
                value = "1";
            else
                value = "0";
            upMap.put(key, value);
            if ("1".equals(mMap.get(ScheduleTable.schRepeatLink))
                    || "3".equals(mMap.get(ScheduleTable.schRepeatLink))) {
                upMap.put(key1, "0");
            } else {
                upMap.put(key1, "2");
            }
            App.getDBcApplication().updateScheduleData(upMap,
                    "where schID=" + mMap.get("schID"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
        super.onRestored(context, oldWidgetIds, newWidgetIds);
    }

    // onUpdate() 在更新 widget 时，被执行，
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        String userid = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "");

        // 创建一个RemoteView
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_b);
        String datea = "今天  " + DateUtil.formatDateMMDD(new Date()) + "  " + StringData();
        try {
            unlist = App.getDBcApplication().queryAllSchData(901, 0, 0);
            todaylist = App.getDBcApplication().queryAllSchData(907, 0, 0);

            mList.addAll(unlist);
            mList.addAll(todaylist);
            ArrayList<Map<String, String>> list = App.getDBcApplication().queryAllSchData(-4, 0, 0);
            if (mList.size() == 0 && list.size() > 0) {
                for (int i = 0; i < 7; i++) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DATE, +i);
                    datea = DateUtil.formatDate(calendar.getTime());
                    mList.addAll(App.getDBcApplication().queryCalenderData(datea));

                    datea = Math.abs(DateUtil.days(datea)) + "天后  " + DateUtil.formatDateMMDD(calendar.getTime()) + "  " + DateUtil.Week(datea);
                    if (mList.size() > 0) {
                        break;
                    }
                }
            }

            if (mList.size() == 0) {
                datea = "今天  " + DateUtil.formatDateMMDD(new Date()) + "  " + StringData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        remoteViews.setTextViewText(R.id.time, datea);

        remoteViews.setEmptyView(R.id.listview, R.layout.app_widget);


        if (!userid.isEmpty()) {

//            Intent intent_m = new Intent(context, MainActivity.class);
//            intent_m.putExtra("ismonth", true);
//            intent_m.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            PendingIntent calendernoIntent = PendingIntent.getActivity(context, 0, intent_m, PendingIntent.FLAG_CANCEL_CURRENT);
//            remoteViews.setOnClickPendingIntent(R.id.month_view, calendernoIntent);

            Intent intent_m = new Intent(CLICK_MONTH);
            intent_m.setComponent(new ComponentName(context, WidgetA.class));
            PendingIntent calendernoIntent = PendingIntent.getBroadcast(context, 0, intent_m, 0);
            remoteViews.setOnClickPendingIntent(R.id.month_view, calendernoIntent);

            cjson(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CYTXJSON, ""));

            if (djsBeanList.size() > 2) {
                String dj1;
                if (djsBeanList.get(0).type == 2) {
                    if ((djsBeanList.get(0).number / 0.5) % 2 == 1) {
                        dj1 = djsBeanList.get(0).number + "";
                    } else {
                        dj1 = (int) djsBeanList.get(0).number + "";
                    }
                } else {
                    dj1 = (int) djsBeanList.get(0).number + "";
                }
                djs1 = dj1 + "\n" + djsBeanList.get(0).timetype;
                remoteViews.setTextViewText(R.id.tv11, dj1);
                remoteViews.setTextViewText(R.id.tv1, djsBeanList.get(0).timetype);

                String dj2;
                if (djsBeanList.get(1).type == 2) {
                    if ((djsBeanList.get(1).number / 0.5) % 2 == 1) {
                        dj2 = djsBeanList.get(1).number + "";
                    } else {
                        dj2 = (int) djsBeanList.get(1).number + "";
                    }
                } else {
                    dj2 = (int) djsBeanList.get(1).number + "";
                }
                djs2 = dj2 + "\n" + djsBeanList.get(1).timetype;
                remoteViews.setTextViewText(R.id.tv21, dj2);
                remoteViews.setTextViewText(R.id.tv2, djsBeanList.get(1).timetype);
            }

            Intent intent1 = new Intent(CLICK_15);
            intent1.putExtra("djs", djs1);
            intent1.setComponent(new ComponentName(context, WidgetA.class));
            PendingIntent djs1 = PendingIntent.getBroadcast(context, 0, intent1, 0);
            remoteViews.setOnClickPendingIntent(R.id.djs1, djs1);

            Intent intent2 = new Intent(CLICK_30);
            intent2.putExtra("djs", djs1);
            intent2.setComponent(new ComponentName(context, WidgetA.class));
            PendingIntent djs2 = PendingIntent.getBroadcast(context, 0, intent2, 0);
            remoteViews.setOnClickPendingIntent(R.id.djs2, djs2);


            if (mList.size() == 0) {
                remoteViews.setViewVisibility(R.id.listview, View.GONE);
                remoteViews.setViewVisibility(R.id.notice, View.VISIBLE);
                remoteViews.setTextViewText(R.id.notice, "本周暂无日程!");
            } else {
                remoteViews.setViewVisibility(R.id.listview, View.VISIBLE);
                remoteViews.setViewVisibility(R.id.notice, View.GONE);

                // 把这个Widget绑定到RemoteViewsService
                Intent intent = new Intent(context, WidgetSetService.class);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds);

                // 设置适配器
                remoteViews.setRemoteAdapter(R.id.listview, intent);

                Intent intent3 = new Intent(CLICK_ITEM_ACTION);
                intent3.setComponent(new ComponentName(context, WidgetA.class));
                intent3.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
                remoteViews.setPendingIntentTemplate(R.id.listview, pendingIntent);
            }

        } else {
            remoteViews.setViewVisibility(R.id.listview, View.GONE);
            remoteViews.setViewVisibility(R.id.notice, View.VISIBLE);
            remoteViews.setTextViewText(R.id.notice, "请先登录!");
        }

        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listview);
    }

    String djs1 = "15\n分钟";
    String djs2 = "30\n分钟";


    public static String StringData() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "天";
        } else if ("2".equals(mWay)) {
            mWay = "一";
        } else if ("3".equals(mWay)) {
            mWay = "二";
        } else if ("4".equals(mWay)) {
            mWay = "三";
        } else if ("5".equals(mWay)) {
            mWay = "四";
        } else if ("6".equals(mWay)) {
            mWay = "五";
        } else if ("7".equals(mWay)) {
            mWay = "六";
        }
        return "周" + mWay;
    }

    private void cjson(String json) {
        try {
            if (json.length() > 0) {
                qcBeanList.clear();
                djsBeanList.clear();

                JSONObject jsonObject = new JSONObject(json);
                JSONArray qc = jsonObject.getJSONArray("qc");
                JSONArray djs = jsonObject.getJSONArray("djs");
                for (int i = 0; i < qc.length(); i++) {
                    JSONObject jsonObject1 = qc.getJSONObject(i);
                    CYTXBean.QcBean qcBean = new CYTXBean.QcBean();
                    qcBean.setTime(jsonObject1.getString("time"));
                    qcBean.setTimetype(jsonObject1.getString("timetype"));
                    int fallback = 1;
                    if (jsonObject1.getString("timetype").equals("凌晨")) {
                        fallback = 1;
                    } else if (jsonObject1.getString("timetype").equals("早上")) {
                        fallback = 2;
                    } else if (jsonObject1.getString("timetype").equals("上午")) {
                        fallback = 3;
                    } else if (jsonObject1.getString("timetype").equals("下午")) {
                        fallback = 4;
                    } else if (jsonObject1.getString("timetype").equals("晚上")) {
                        fallback = 5;
                    }
                    qcBean.setType(jsonObject1.optInt("type", fallback));
                    qcBeanList.add(qcBean);
                }
                for (int i = 0; i < djs.length(); i++) {
                    JSONObject jsonObject1 = djs.getJSONObject(i);
                    CYTXBean.DjsBean djsBean = new CYTXBean.DjsBean();
                    djsBean.setNumber(jsonObject1.getDouble("number"));
                    djsBean.setTimetype(jsonObject1.getString("timetype"));
                    int fallback = 1;
                    if (jsonObject1.getString("timetype").equals("分钟")) {
                        fallback = 1;
                    } else if (jsonObject1.getString("timetype").equals("小时")) {
                        fallback = 2;
                    } else if (jsonObject1.getString("timetype").equals("天")) {
                        fallback = 3;
                    }
                    djsBean.setType(jsonObject1.optInt("type", fallback));
                    djsBeanList.add(djsBean);
                }
                Comparator<CYTXBean.QcBean> comparator = new Comparator<CYTXBean.QcBean>() {
                    @Override
                    public int compare(CYTXBean.QcBean lhs, CYTXBean.QcBean rhs) {
                        if (lhs.getType() == rhs.getType()) {
                            return lhs.getTime().compareTo(rhs.getTime());
                        } else {
                            return lhs.getType() - rhs.getType();
                        }
                    }
                };
                Collections.sort(qcBeanList, comparator);
                Comparator<CYTXBean.DjsBean> comparator1 = new Comparator<CYTXBean.DjsBean>() {
                    @Override
                    public int compare(CYTXBean.DjsBean lhs, CYTXBean.DjsBean rhs) {
                        if (lhs.getType() == rhs.getType()) {
                            return (int) (lhs.getNumber() * 60) - (int) (rhs.getNumber() * 60);
                        } else {
                            return lhs.getType() - rhs.getType();
                        }
                    }
                };
                Collections.sort(djsBeanList, comparator1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return "V" + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "V6.3.2";
        }
    }

    private void updateLoginDate(final Context context) {
        String userId = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0");
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if (!userId.substring(0, 1).equals("-")) {
                String path = URLConstants.更新用户最后登录时间 + userId
                        + "&userOpenId=1&version=" + getVersion(context) + "&phoneType="
                        + android.os.Build.MANUFACTURER + "-"
                        + android.os.Build.MODEL.replace(" ", "");// android.os.Build.MODEL
                StringRequest request = new StringRequest(Request.Method.GET, path,
                        new Response.Listener<String>() {

                            @Override
                            public void onResponse(String s) {
                                if (!TextUtils.isEmpty(s)) {
                                    try {
                                        Gson gson = new Gson();
                                        SuccessOrFailBean bean = gson.fromJson(s,
                                                SuccessOrFailBean.class);
                                        if (bean.status == 0) {
                                            sharedPrefUtil.putString(context,
                                                    ShareFile.USERFILE,
                                                    ShareFile.ENDLOGINDATE,
                                                    DateUtil.formatDate(new Date()));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {

                    }
                });
                request.setTag("down");
                request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                App.getHttpQueues().add(request);
            }
        } else {
            int sid = Math.abs(Integer.valueOf(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0")));
            String path = URLConstants.新游客试用 + "?phoneType=" + android.os.Build.MODEL.replace(" ", "") + "&id=" + sid + "&version=" + getVersion(context) + "&pushMac=" + JPushInterface.getRegistrationID(context);
            StringRequest request = new StringRequest(Request.Method.GET, path,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String result) {
                            String re = result;
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            request.setTag("resgin");
            request.setRetryPolicy(new DefaultRetryPolicy(3000, 1, 1.0f));
            App.getHttpQueues().add(request);
        }
    }
}
